import * as vscode from 'vscode';
import { generateHTML } from '../page/webContent';
import { openDatabase } from '../db';
import { gunzip } from 'zlib';
import { promisify } from 'util';

const gunzipPromise = promisify(gunzip);

const BOOK_CHAPTERS = 'select id, chapter from tb_chapter tc where book_id = ?';
const CHAPTER_CONTENT = 'select gzip_content from tb_chapter where id = ?';

// type BookInfo = { name: string; author: string };

export type Chapter = { id: number; chapter: string };
export type ChapterContent = { gzip_content: Buffer };

const openedPanel = new Map<number, vscode.WebviewPanel>();

export async function openBook(id: number, label: string) {
	let panel = openedPanel.get(id);
	if (panel) {
		panel.reveal(1);
		return;
	}
	const db = openDatabase();
	const chapters = db.prepare<unknown[], Chapter>(BOOK_CHAPTERS).all(id);
	if (chapters.length <= 0) {
		vscode.window.showInformationMessage(`Book not found: ${label}`);
		return;
	}
	const contentStatement = db.prepare<unknown[], ChapterContent>(CHAPTER_CONTENT);
	const firstChapterContent = contentStatement.get(chapters[0].id);
	const firstChapterText = firstChapterContent
		? (await gunzipPromise(firstChapterContent.gzip_content)).toString('utf-8')
		: '';

	//vscode.window.
	panel = vscode.window.createWebviewPanel('e-reader-book', label, vscode.ViewColumn.One, {
		enableFindWidget: true,
		retainContextWhenHidden: true,
		enableCommandUris: true,
		enableScripts: true,
	});
	openedPanel.set(id, panel);
	panel.webview.html = await generateHTML(chapters, firstChapterText);
	panel.webview.onDidReceiveMessage(async (message) => {
		if (message.command === 'openChapter') {
			const chapterContent = contentStatement.get(message.id);
			const chapterText = chapterContent ? (await gunzipPromise(chapterContent.gzip_content)).toString('utf-8') : '';
			panel.webview.postMessage(chapterText);
		} else {
			vscode.window.showErrorMessage('invalid command: ' + message.command);
		}
	});
	panel.onDidDispose(() => {
		openedPanel.delete(id);
	});
}
